package de.dopichaj.labrador.search.merge.pattern;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;

import de.dopichaj.labrador.search.hit.Hit;
import de.dopichaj.labrador.search.merge.Merge;


/**
 * This merge implementation updates the scores based on context patterns.
 * 
 * Note that each pattern instance should only be added to one active PatternMerge
 * instance (because of internal state).
 */
public final class PatternMerge extends Merge implements ScoreBooster {

    /**
     * Output/membership pairs.
     */
    private static final class OutputMembership {
        public OutputMembership(double output, double membership) {
            this.output = output;
            this.membership = membership;
        }
        public double output;
        public double membership;
    }
    private final Map<Hit, List<OutputMembership>> scoreChanges =
        new HashMap<Hit, List<OutputMembership>>();
    private final AbstractPattern[] patterns;
    
    public PatternMerge(AbstractPattern... patterns) {
        this.patterns = new AbstractPattern[patterns.length];
        for (int i = 0; i < patterns.length; i++) {
            final AbstractPattern pattern = patterns[i];
            this.patterns[i] = pattern;
            pattern.setBooster(this);
        }
    }
    
    
    
    @Override
    public int decideMerge(Hit parent, SortedSet<Hit> children) {
        
        for (final AbstractPattern pattern : patterns) {
            pattern.applyTo(parent, children);
        }
        for (Hit child : children) {
            updateScore(child);
            scoreChanges.remove(child);
        }
        
        return DO_NOT_MERGE;
    }

    /* (non-Javadoc)
     * @see de.dopichaj.labrador.search.merge.pattern.ScoreBooster#boostScore(de.dopichaj.labrador.search.hit.Hit, double, double)
     */
    public void boostScore(Hit hit, double output, double membership) {

        if (membership > 1 || membership < 0) {
            throw new IllegalArgumentException("Membership must lie between 0 and 1, is " + membership);
        }
        if (membership != 0) {
            List<OutputMembership> l = scoreChanges.get(hit);
            if (l == null) {
                l = new ArrayList<OutputMembership>();
                scoreChanges.put(hit, l);
            }
            l.add(new OutputMembership(output, membership));
        }
    }
    
    public void boostScoreUpwards(Hit hit, double output, double membership) {
        
        if (membership != 0) {
            double damp = 1.0;
            Hit currentHit = hit;
            while (currentHit != null) {
                boostScore(currentHit, output, membership * damp);
                
                currentHit = tree.getParent(currentHit);
                damp *= 0.75;
            }
        }
    }
    
    /* (non-Javadoc)
     * @see de.dopichaj.labrador.search.merge.pattern.ScoreBooster#boostScores(java.util.Collection, double, double)
     */
    public void boostScores(Collection<Hit> hits, double output, double membership) {
        for (Hit hit : hits) {
            boostScore(hit, output, membership);
        }
    }

    private void updateScore(Hit hit) {
        if (scoreChanges.containsKey(hit)) {

            // calculate final factor using center of area method
            double numerator   = 0;
            double denominator = 0;
            for (OutputMembership om : scoreChanges.get(hit)) {
                numerator   += om.membership * om.output;
                denominator += om.membership;
            }
            double factor = numerator / denominator;
            
            // update score
            float newScore = (float)(hit.getScore() * factor);
            hit.setScore(newScore);
            
        }
    }
    
    @Override
    public void finishMerge() {
        
        for (Hit hit : scoreChanges.keySet()) {
            updateScore(hit);
        }
        scoreChanges.clear();
    }



    @Override
    public String getDescription() {
        final StringBuilder builder = new StringBuilder("Patterns:");
        
        for (final AbstractPattern pattern : patterns) {
            
            builder.append(" ").append(pattern.getDescription());
        }
        return builder.toString();
    }
}
/*
Copyright (c) 2005-2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/